﻿using CommonLibrary.Models;
using CommonLibrary.WorkFlow.Enums;
using CommonLibrary.WorkFlow.Exceptions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CommonLibrary.WorkFlow
{
    public class ViewFlow : IWorkFlow
    {
        private WorkFlowManager manager;

        public ViewFlow(WorkFlowManager manager)
        {
            this.manager = manager;
        }

        public WorkResult AddTaskObject(Step step, DataRow task, DataRow flowObject)
        {
            var action = (ActionType)(int)task["actiontype"];
            switch (action)
            {
                case ActionType.Single:
                    SingleMode(task, flowObject);
                    break;

                case ActionType.Multi:
                    MultiMode(task, flowObject);
                    break;
            }

            return WorkResult.Complete;
        }

        public WorkResult Execute(DataRow taskObject, Dictionary<string, object> values)
        {
            throw new NotImplementedException();
        }

        private void SingleMode(DataRow task, DataRow flowObject)
        {
            DbHelper.InsertFlowObjectCC(manager.Database, (int)flowObject["id"], (int)task["touser"]);

            MailManager.SendCCEmail(
                manager.Database,
                (int)task["touser"],
                (int)flowObject["createuserid"],
                DbHelper.GetWorkFlow(manager.Database, (int)flowObject["flowid"])["name"].ToString());
        }

        private void MultiMode(DataRow task, DataRow flowObject)
        {
            var users = (int[])task["touserlist"];
            var name = DbHelper.GetWorkFlow(
                            manager.Database,
                            (int)flowObject["flowid"])["name"].ToString();
            foreach (var user in users)
            {
                DbHelper.InsertFlowObjectCC(manager.Database, (int)flowObject["id"], user);

                MailManager.SendCCEmail(
                    manager.Database,
                    user,
                    (int)flowObject["createuserid"],
                    name);
            }
        }
    }
}
